var mongoose = require('mongoose'),
	Question = mongoose.model('Question'),
	Q = require('q'),
	_ = require('lodash');

var PAGE_COUNT = 2;

module.exports.queryPageQuestions = function(data){
	var tmp = {};
	if(data){
		
	}
	return Question.find(tmp).count().exec().then(
		function(count){

			if(count > 0){
				console.log(tmp.page -1)
				return Question.find(tmp).sort('type').skip((data.page -1) * PAGE_COUNT).limit(PAGE_COUNT).exec().then(
						function(res){
							return {
								count: _.floor((count - 1) / PAGE_COUNT) + 1,
								list : res,
								flag:true
							};
						},
						function(err){
							console.error(err);
							return {count:0,list:[],flag:false,info:err};
						}
					);
			}else{
				return {count:0,list:[],flag:true}
			}
		},function(err){
			console.error(err);
			return {count:0,list:[],flag:false,info:err}
		}
	);
}

module.exports.queryQuestions = function(exam){
	console.log(exam);
	console.log(typeof  exam);
	var defered = Q.defer();
	Question.find({},null,{sort:{type:1}},function(err,data){
		if(err){
			defered.reject(err);
		}
		defered.resolve(data);
	});
	return defered.promise;
};

module.exports.addQuestions = function(question){
	var q = {
		title:'test113',
		type : '选择题3',
		res : ['为啥32','怎么23','啊哈44','好吧55'],
		exam:1,
		createTime : new Date(),
		modifyTime: new Date()
	};
	var defered = Q.defer();
	Question.findOneAndUpdate({title:'test12'},q,{upsert:true,new:true},function(err,que){
		if(err){
			defered.reject(err);
		}
		defered.resolve(que);
	});
	return defered.promise;
};